import Score from './Score'
import Card from './Card'
import Info from './Info'
import { play } from './skill'
import { Component, createEffect, createMemo, createSignal, on } from 'solid-js'
import Top from './Top'
import { uniqTimer } from './utils'
import { Config, GameProvider, useGame } from './game'

let defaultConfig: Config = {
  autoRematch: -1,
  saveStat: false,

  agent: [[[255,0,0,0,0,0,0,0],[147,108,0,0,0,0,0,0],[159,46,50,0,0,0,0,0],[34,182,39,0,0,0,0,0],[66,56,133,0,0,0,0,0],[9,119,127,0,0,0,0,0]],[[133,0,0,0,122,0,0,0],[63,124,0,0,68,0,0,0],[42,71,97,3,42,0,0,0],[96,16,27,99,17,0,0,0],[51,36,41,45,82,0,0,0],[23,83,56,75,18,0,0,0]],[[134,0,0,0,117,4,0,0],[26,101,0,0,106,22,0,0],[16,10,82,28,44,75,0,0],[16,23,11,102,53,50,0,0],[67,38,17,31,39,63,0,0],[105,25,47,34,21,23,0,0]],[[0,0,0,0,0,0,255,0],[34,66,0,0,54,64,37,0],[26,36,15,37,23,45,73,0],[18,64,10,28,39,45,51,0],[36,25,32,60,36,32,34,0],[47,40,19,43,46,48,12,0]],[[0,0,0,0,0,0,255,0],[69,51,0,0,25,99,11,0],[43,34,14,51,48,19,46,0],[40,15,45,63,14,26,52,0],[50,40,42,16,23,39,45,0],[63,34,55,25,4,32,42,0]],[[0,0,0,0,0,0,56,199],[0,0,0,0,0,0,0,255],[0,0,0,0,0,0,0,255],[0,0,0,0,0,0,0,255],[0,0,0,0,0,0,0,255],[0,0,0,0,0,0,0,255]]],

  skill: [{"cost":-1,"name":"集","versus":[0,0,0,0,-1,-1,-1,-1]},{"cost":0,"name":"小防","versus":[0,0,0,0,0,-1,-1,-1]},{"cost":0,"name":"中防","versus":[0,0,0,0,-1,0,-1,-1]},{"cost":1,"name":"大防","versus":[0,0,0,0,0,0,0,-1]},{"cost":1,"name":"小波","versus":[1,0,1,0,0,-1,-1,-1]},{"cost":2,"name":"中波","versus":[1,1,0,0,1,0,-1,-1]},{"cost":3,"name":"大波","versus":[1,1,1,0,1,1,0,-1]},{"cost":5,"name":"黑洞","versus":[1,1,1,1,1,1,1,0]}],
}

const Gui: Component = () => {
  const { store, round, rematch } = useGame()
  const [cd, setCd] = createSignal(false)

  const theirsPlay = createMemo(on(() => store.update,
    () => play(store.agent, store.their, store.my)))

  const [setTmCd] = uniqTimer(setTimeout, clearTimeout)
  const cdFor = (time: number) => {
    setCd(true)
    setTmCd(() => setCd(false), time)
  }

  const [setTmRematch, clearTmRematch] = uniqTimer(setTimeout, clearTimeout)
  createEffect(() => {
    const time = store.autoRematch
    if (time > 0 && store.result != 0) {
      setTmRematch(() => {
        rematch()
      }, time)
    } else {
      clearTmRematch()
    }
  })

  return <>
    <Score></Score>
    <Top></Top>
    <Info></Info>
    <Card
      disable={cd() || store.result != 0}
      onClick={skill1 => {
        round(skill1, theirsPlay())
        cdFor(400)
      }}
    ></Card>
  </>
}

const App = () =>
  <GameProvider defaultConfig={defaultConfig}>
    <Gui></Gui>
  </GameProvider>

export default App
